from django.shortcuts import render
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status
from rest_framework.pagination import PageNumberPagination
from rest_framework.decorators import api_view

from .models import PersonInfo, Vocation
from .serializers import MySerializer

# Create your views here.
@api_view(['GET', 'POST'])
def vocationDef(request):
    if request.method == 'GET':
        q = Vocation.objects.all()
        pg = PageNumberPagination()
        p = pg.paginate_queryset(q, request)
        serializer = MySerializer(p, many=True)
        return Response(serializer.data)
    elif request.method == 'POST':
        data = request.data
        id = data['name']
        data['name'] = PersonInfo.objects.filter(id=id).first()
        instance = Vocation.objects.filter(id=data.get('id', 0))
        if instance:
            MySerializer().update(instance, data)
        else:
            MySerializer().create(data)
        return Response('Done', status=status.HTTP_201_CREATED)

class vocationClass(APIView):
    def get(self, request):
        q = Vocation.objects.all()
        pg = PageNumberPagination()
        p = pg.paginate_queryset(q, request, self)
        serializer = MySerializer(p, many=True)
        return Response(serializer.data)

    def post(self, request):
        data = request.data
        id = data['name']
        data['name'] = PersonInfo.objects.filter(id=id).first() # 替换成PersonInfo对象
        instance = Vocation.objects.filter(id=data.get('id', 0))
        if instance:
            MySerializer().update(instance, data)
        else:
            MySerializer().create(data)
        return Response('Done', status=status.HTTP_201_CREATED)